#pragma GCC optimize(2)
#include <bits/stdc++.h>

using namespace std;
#define int long long
const int inf = 0x3f3f3f3f3f3f3f3f;

void solve()
{
    int n, m;
    cin >> n >> m;
    vector<int> a(n), b(m);
    for (int i = 0; i < n; i++) cin >> a[i];
    for (int i = 0; i < m; i++) cin >> b[i];
    {
        vector<int> c = a, d = b;
        c.resize(distance(c.begin(), unique(c.begin(), c.end())));
        d.resize(distance(d.begin(), unique(d.begin(), d.end())));
        if (c != d)
        {
            cout << -1 << endl;
            return;
        }
    }
    vector<int> c, d;
    int cur = a[0];
    int cnt = 1;
    for (int i = 1; i < n; i++)
    {
        if (a[i] != cur)
        {
            c.push_back(cnt);
            cnt = 1;
            cur = a[i];
        }
        else cnt++;
    }
    c.push_back(cnt);
    cur = b[0];
    cnt = 1;
    for (int i = 1; i < m; i++)
    {
        if (b[i] != cur)
        {
            d.push_back(cnt);
            cnt = 1;
            cur = b[i];
        }
        else cnt++;
    }
    d.push_back(cnt);
    if (c.size() != d.size())
    {
        cout << -1 << endl;
        return;
    }
    for (int i = 0; i < c.size(); i++)
    {
        if (d[i] - c[i] < 0)
        {
            cout << -1 << endl;
            return;
        }
        if (c[i] == 0) continue;
        c[i] = ceil(log2l(ceil(d[i] / (double)c[i])));
    }
    cout << *max_element(c.begin(), c.end()) << endl;
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int _ = 1;
    cin >> _;
    while (_--)
    {
        solve();
    }
    return 0;
}